package main.controller.admin;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import main.RequestHelper;
import main.GlobalConfig;
import main.ResponseHelper;
import main.StringHelper;
import main.cipher.MD5Utils;
import main.database.AccountHelper;
import main.database.DatabaseMan;
import org.bson.Document;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
public class UploadPageController {
    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }

        try {
            String originalFilename = file.getOriginalFilename();
            int dot = originalFilename.lastIndexOf('.');
            String extension = file.getOriginalFilename().substring(dot + 1);

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
            String filePath = "dailyPicture/" + now.format(formatter) + StringHelper.getAlphaNumericString(8) + "." + extension;
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath);
            Files.write(path, bytes);

            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfDailyPicture);
            Document document = new Document("imagepath", filePath);
            collection.insertOne(document);

            redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + originalFilename + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "uploadStatus.html";
    }

    @PostMapping("/api/uploadportrait")
    public ResponseEntity<?> uploadPortrait(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        boolean isExist = AccountHelper.isExistFromUUID(uuid);

        JSONObject jo = null;

        if (!isExist) {
            jo = ResponseHelper.createBasicJsonObject(404, "不存在的用户或者未登录的用户");
        }
        else {
            String originalFilename = file.getOriginalFilename();
            int dot = originalFilename.lastIndexOf('.');
            String extension = file.getOriginalFilename().substring(dot + 1);

            if (extension.equals("png") || extension.equals("jpeg") || extension.equals("jpg") || extension.equals("bmp")) {
                try {
                    //read image width and height
                    BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                    int width = bufferedImage.getWidth();
                    int height = bufferedImage.getHeight();

                    if (width == 128 && height == 128) {
                        LocalDateTime now = LocalDateTime.now();
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
                        String filePath = "src/main/resources/static/uploadfile/" + now.format(formatter) + StringHelper.getAlphaNumericString(8) + "." + extension;
                        byte[] bytes = file.getBytes();
                        Path path = Paths.get(filePath);
                        Files.write(path, bytes);

                        String md5 = MD5Utils.getChecksum(bytes);

                        // 搜索同样内容的文件的存在性
                        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfDailyPicture);
                        FindIterable<Document> documents = collection.find(Filters.eq("md5", md5)).projection(Projections.include("md5", "imagepath"));
                        MongoCursor<Document> cursor = documents.iterator();
                        jo = ResponseHelper.createBasicJsonObject(200, "ok");
                        if (cursor.hasNext()) {
                            Document doc = cursor.next();
                            filePath = doc.get("imagepath").toString();
                        } else {
                            Document document = new Document("imagepath", filePath)
                                    .append("md5", md5);
                            collection.insertOne(document);
                        }
                        jo.put("path", filePath);

                        //TODO: 存储到用户数据库

                    }
                    else {
                        jo = ResponseHelper.createBasicJsonObject(404, "图片尺寸不对");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    jo = ResponseHelper.createBasicJsonObject(404, "文件格式错误");
                }
            }
            else {
                jo = ResponseHelper.createBasicJsonObject(404, "图片必须是png、jpeg、jpg、bmp结尾");
            }
        }

        return ResponseEntity.ok(jo.toString());
    }
}
